package net.sinmetal.twitcockpit.model;

import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import net.sinmetal.twitcockpit.modelvar.AutoPostVar;
import net.sinmetal.twitcockpit.util.IntegerUtil;
import net.sinmetal.twitcockpit.util.StringUtil;

import org.slim3.datastore.Attribute;
import org.slim3.datastore.Datastore;
import org.slim3.datastore.Model;

import com.google.appengine.api.datastore.Key;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

/**
 * 自動Postする内容
 *
 * @author Sinmetal
 *
 */
@Model(schemaVersion = 1)
public class AutoPost implements Serializable {

    private static final long serialVersionUID = 1L;

    @Attribute(primaryKey = true)
    private Key key;

    @Attribute(version = true)
    private Long version;

    @Attribute(lob = true)
    private String autoPostVarJson;

    /**
     * Returns the key.
     *
     * @return the key
     */
    public Key getKey() {
        return key;
    }

    /**
     * Sets the key.
     *
     * @param key
     *            the key
     */
    public void setKey(Key key) {
        this.key = key;
    }

    /**
     * Returns the version.
     *
     * @return the version
     */
    public Long getVersion() {
        return version;
    }

    /**
     * Sets the version.
     *
     * @param version
     *            the version
     */
    public void setVersion(Long version) {
        this.version = version;
    }

    /**
     * @return autoPostVarJson
     */
    public String getAutoPostVarJson() {
        return autoPostVarJson;
    }

    /**
     * @param autoPostVarJson
     *            セットする autoPostVarJson
     */
    public void setAutoPostVarJson(String autoPostVarJson) {
        this.autoPostVarJson = autoPostVarJson;
    }

    /**
     * AutoPostVars取得
     *
     * @return
     */
    public List<AutoPostVar> getAutoPostVars() {
        if (StringUtil.isEmpty(this.autoPostVarJson)) {
            return new ArrayList<AutoPostVar>();
        }
        Type autoPostVarsType = new TypeToken<List<AutoPostVar>>() {
        }.getType();
        Gson gson = new Gson();
        return gson.fromJson(this.autoPostVarJson, autoPostVarsType);
    }

    /**
     * AutoPostVar追加
     *
     * 毎回JSON変換を行うので、実行回数に気を付けること<br />
     * 同じIDがあった場合、上書きする
     *
     * @param autoPostVar
     */
    public void addAutoPostVar(AutoPostVar autoPostVar) {
        List<AutoPostVar> autoPostVars = getAutoPostVars();
        for (AutoPostVar postVar : autoPostVars) {
            if (postVar.getId().equals(autoPostVar.getId())) {
                autoPostVars.remove(postVar);
                break;
            }
        }
        autoPostVars.add(autoPostVar);
        Gson gson = new Gson();
        this.autoPostVarJson = gson.toJson(autoPostVars);
    }

    /**
     * 指定されたIDのAutoPostVarを削除する
     *
     * 毎回JSON変換を行うので、実行回数に気を付けること<br />
     *
     * @param id
     */
    public void deleteAutoPostVar(String id) {
        List<AutoPostVar> autoPostVars = getAutoPostVars();
        for (AutoPostVar postVar : autoPostVars) {
            if (id.equals(postVar.getId())) {
                autoPostVars.remove(postVar);
                break;
            }
        }
        Gson gson = new Gson();
        this.autoPostVarJson = gson.toJson(autoPostVars);
    }

    /**
     * Key生成
     *
     * @param hour
     * @param minute
     * @return
     */
    public static Key createKey(int hour, int minute) {
        validateHour(hour);
        validateMinute(minute);

        final int FIXED_VALUE = 10000; // KeyのIDに0は使えないため、常に10000以上になるようにする
        final int MINUTE_DIGIT = 100;
        int key = hour * MINUTE_DIGIT + minute + FIXED_VALUE;
        return Datastore.createKey(AutoPost.class, key);
    }

    /**
     * インスタンス生成
     *
     * @return
     */
    public static AutoPost getInstance() {
        AutoPost instance = new AutoPost();
        instance.setAutoPostVarJson("");
        return instance;
    }

    /**
     * Key生成時の"時"検証
     *
     * @param hour
     */
    private static void validateHour(int hour) {
        final int MINI_HOUR = 0;
        final int MAX_HOUR = 23;

        if (!IntegerUtil.isRange(hour, MINI_HOUR, MAX_HOUR)) {
            String message =
                String.format(
                    "hour not fall within the range : value = %s",
                    hour);
            throw new IllegalArgumentException(message);
        }
    }

    /**
     * Key生成時の"分"検証
     *
     * @param minute
     */
    private static void validateMinute(int minute) {
        final int MINI_MINUTE = 0;
        final int MAX_MINUTE = 45;
        if (!IntegerUtil.isRange(minute, MINI_MINUTE, MAX_MINUTE)) {
            String message =
                String.format(
                    "minute not fall within the range : value = %s",
                    minute);
            throw new IllegalArgumentException(message);
        }

        final int CRON_INTERVAL_TIME = 15;
        if (minute % CRON_INTERVAL_TIME != 0) {
            String message =
                String.format(
                    "minute not divisible by cron time : value = %s",
                    minute);
            throw new IllegalArgumentException(message);
        }
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((key == null) ? 0 : key.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        AutoPost other = (AutoPost) obj;
        if (key == null) {
            if (other.key != null) {
                return false;
            }
        } else if (!key.equals(other.key)) {
            return false;
        }
        return true;
    }
}